<template>
	<view class="index">
		<view class="head-bg" :style="{height: currentCategory.name !== '品牌'?'454rpx':'263rpx'}">
			<image :src="STATIC_URL + 'dlbj.png'" mode="aspectFill"></image>
		</view>
		<u-navbar :is-back="false" :background="background" :border-bottom="false" title-color="#FFF">
			<view @click="skip">
				<u-icon name="nav-back" color="#fff" size="44"></u-icon>
			</view>
			<view class="search" @click="searchNavigate">
				<u-icon name="search"></u-icon>
				<text class="hint">请输入搜索的内容</text>
			</view>
		</u-navbar>
		<view class="sticky" :style="{'top': offsetTop + 'px'}">
			<u-tabs :list="categories" inactive-color="#FFF" :bg-color="background.background" active-color="#FFFFFF"
				@change="changeTab" :current="current"></u-tabs>
		</view>
		<view class="index-swiper" v-if="current === 0">
			<u-swiper :list="swiperLists" height="398" :border-radius="10" mode="dot" @click="openSwiper"></u-swiper>
		</view>
		<view class="index-ad" v-if="current === 0">
			<template v-for="(item, index) in ads">
				<view :key="index" class="index-ad-item">
					<image class="icon" :src="`${STATIC_URL}index/little-${index + 1}.png`" mode="aspectFit" />
					<view class="text">
						{{ item.name }}
					</view>
				</view>
			</template>
		</view>
		<!-- 品牌 -->
		<view class="container" v-if="current === 0">
			<Brand :data="brands" />
			<vip-card :checked="false"></vip-card>
			<Seckill :list='seckList' />
			<Classic :list="recommendGood" />
		</view>
		<view class="sticky" :style="{top: offsetTop + 'px'}" v-if="current === 0">
			<u-tabs :list="indexTags" active-color="#CB712B" :current="indexTagCurrent" @change="changeIndexTag" />
		</view>
		<view class="index-content">
			<BrandList :list='allBrands' v-if="currentCategory.name === '品牌'" />
			<Products :list="goods" v-else />
		</view>
		<ad-modal :value.sync="showAD" :info="adInfo"></ad-modal>
		<packet-modal @nullPacket="showAD = true" :showAD="showAD"></packet-modal>

		<pageCont />
	</view>
</template>

<script>
	import {
		getAccessToken,
		getCode
	} from "@/utils/code";
	import {
		loginPrefix
	} from "@/utils/permission";
	// import GoodsItem from "./components/item";
	import {
		indexSwiper,
		indexGoods,
		OEMGetName,
		test,
		brandInfoApi,
		indexRecommendApi,
		goodsListApi
	} from "@/utils/api.js";
	import {
		indexTagApi,
		homeDataApi,
		adWindowApi
	} from '@/api/index.js'
	import {
		mapActions,
		mapGetters
	} from "vuex";
	import {
		shareLevel
	} from "@/utils/api";
	import vipCard from "@/components/vipCard.vue"
	import Brand from "./components/brand.vue"
	import Seckill from "./components/seckill.vue"
	import Classic from "./components/classic.vue"
	import Products from "@/components/products/index.vue"
	import BrandList from "./components/brand-list.vue"
	import AdModal from "@/components/ad-modal.vue"
	import PacketModal from "@/components/packet_modal/index.vue"
	import pageCont from '@/components/pageContainer.vue'
	let limit = 10;
	export default {
		components: {
			// GoodsItem,
			vipCard,
			Brand,
			Seckill,
			Classic,
			Products,
			BrandList,
			AdModal,
			PacketModal,
			pageCont
		},
		data() {
			return {
				swiperLists: [],
				categories: [],
				current: 0,
				brands: [],
				// 全部分类,不能一次性全部加载
				allBrands: [],
				page: 1,
				ads: [{
						name: "奥莱授权",
					},
					{
						name: "保证正品",
					},
					{
						name: "线下门店",
					},
					{
						name: "奢品养护",
					},
				],
				kinds: [{
						icon: "fz",
						text: "服装",
					},
					{
						icon: "xb",
						text: "鞋包",
					},
					{
						icon: "sp",
						text: "饰品",
					},
					{
						icon: "rh",
						text: "日化",
					},
					{
						icon: "mb",
						text: "名表",
					},
				],
				goods: [],
				cur: 1,
				total: 0,
				test: "",
				// 推荐商品
				recommendGood: [],
				// 秒杀商品
				seckList: [],
				finished: false,
				background: {
					background: "transparent"
				},
				indexTags: [],
				indexTagCurrent: 0,
				offsetTop: 0,
				adInfo: null,
				showAD: false,
			};
		},
		computed: {
			...mapGetters(["userInfo", "shareId", 'isVip']),
			currentCategory() {
				let category = this.categories[this.current]
				return category
			}
		},
		watch: {
			watch: {
				current(val) {
					this.resetInfo()
					if (val === 0) {
						this.getHomeData()
					} else if(val === 1) {
			
					} else {
						this.initGoodsList()
					}
				}
			},
		},
		onLoad(ops) {
			const scene = decodeURIComponent(ops.scene);
			// console.log(query)
			this.getSwiper();
			// this.initGoodsList();
			this.getData();
			this.setOffsetTop()
			this.getIndexTag()
			this.getADWindow();
			// 分享Id
			if (ops) {
				ops.user_id && this.saveShareId(ops.user_id);
				if (uni.getStorageSync("token")) {
					this.setUserInfo().then(() => {
						// this.setOrderAddress(this.userInfo.city);
						console.log("this.shareId", this.shareId);
						if (this.shareId) {
							shareLevel({
								id: this.shareId,
							}).then((resp) => {
								console.log("用户上下级绑定", resp);
							});
						}
					});
				}
			}
			// 监听事件总线
			this.$bus.$on('changeTab', this.changeTab)
		},
		onReady() {
			if (uni.getStorageSync("token")) {
				OEMGetName().then((resp) => {
					console.log("获取OEM分享名称", resp);
					if (resp.code == 200 && resp.data) {
						uni.setNavigationBarTitle({
							title: resp.data,
						});
					}
				});
			}
		},
		onReachBottom() {
			if (this.finished || this.current === 0 || this.current === 1) return
			this.cur++;
			this.initGoodsList()
		},
		onPageScroll({
			scrollTop
		}) {
			let ratio = 0
			if (scrollTop > 100) {
				ratio = 1
			} else {
				ratio = parseFloat(scrollTop / 100).toFixed(2)
			}
			this.background.background = `rgba(203,114,44,${ratio})`
		},
		onShareAppMessage(res) {
			var that = this;
			if (res.from == "menu") {
				uni.hideShareMenu();
				if (this.userInfo.id) {
					uni.showShareMenu();
					return {
						// title: this.shareData.title,
						title: "COOLUX国际奢侈品折扣店",
						path: this.userInfo.id ?
							"/pages/tabs/index/index?user_id=" + that.userInfo.id : "/pages/tabs/index/index",
						// imageUrl: this.shareData.imageUrl,
						desc: "desc",
						content: "content",
						// 微信小程序无法支持判断分享是否成功
						success(res) {
							console.log("分享", res);
							uni.showToast({
								title: "分享成功",
								success: () => {},
							});
						},
						fail(res) {
							console.log("失败啦啦啦啦", res);
							uni.showToast({
								title: "分享失败",
								icon: "none",
							});
						},
					};
				} else {
					uni.hideShareMenu();
					uni.showModal({
						content: "未登录状态下分享无法绑定上下级关系",
						success: ({
							confirm
						}) => {
							if (confirm) {
								uni.showShareMenu();
								return {
									title: "COOLUX",
									path: this.userInfo.id ?
										"/pages/tabs/index/index?user_id=" + this.userInfo.id :
										"/pages/tabs/index/index",
									// imageUrl: this.shareData.imageUrl,
									desc: "desc",
									content: "content",
								};
							}
						},
					});
				}
			}
		},
		methods: {
			...mapActions(["setUserInfo", "setOrderAddress", "saveShareId"]),
			
			skip() {
				uni.redirectTo({
					url: '/pages/index/index?index=2'
				})
			},
			changeTab(index) {
				this.current = index
			},
			async getADWindow() {
				let {
					data
				} = await adWindowApi()
				if(data && data.length){
					this.adInfo = data[0]
					this.showAD = true
				}
			},
			// 轮播图跳转
			openSwiper(index) {
				let data = this.swiperLists[index]
				switch (data.link_type) {
					case 3:
						uni.navigateTo({
							url: `/pages/goodsDetails/goodsDetails?id=${data.link}`
						})
						break;
					case 2:
						uni.navigateTo({
							url: data.link
						})
						break;
				}
			},
			async getIndexTag() {
				let {
					data
				} = await indexTagApi()
				this.indexTags = data.map(item => {
					return {
						...item,
						name: item.type_name
					}
				})
				this.getHomeData()
			},
			setOffsetTop() {
				uni.getSystemInfo({
					success: (res) => {
						this.offsetTop = res.statusBarHeight + 44
					}
				})
			},
			resetInfo() {
				this.finished = false
				this.cur = 1
				this.goods = []
			},
			async getData() {
				// 品牌部分数据
				let {
					data
				} = await brandInfoApi()
				this.categories = data.category.map(item => {
					return {
						...item,
						name: item.goods_cate_name
					}
				})
				this.categories.unshift({
					name: '品牌'
				})
				this.categories.unshift({
					name: '首页'
				})
				this.allBrands = data.brand.slice(0, 50)
				// 推荐部分数据
				let res = await indexRecommendApi({
					recmode_num: 2,
					get_brand: 1
				})
				this.brands = res.data.brand
				this.recommendGood = res.data.goods
				let seckill = await indexRecommendApi({
					recmode_num: 1
				})
				this.seckList = seckill.data.goods
				// 首页下不拉取此接口的数据
				if (this.current !== 0) {
					await this.initGoodsList()
				}
			},
			// 获取轮播
			getSwiper() {
				indexSwiper().then((resp) => {
					// console.log(resp)
					this.swiperLists = resp.data;
				});
			},
			jumpPage() {
				if (this.userInfo.vip_level != 0) {
					uni.navigateTo({
						url: "../memberIntro/memberIntro"
					})
				} else {
					this.vipNavigate(1)
				}
			},
			async getHomeData() {
				let tag = this.indexTags[this.indexTagCurrent]
				console.log('tag==>', tag);
				let {
					data
				} = await homeDataApi({
					type_id: tag.id
				})
				this.goods = data
			},
			// 商品列表
			async initGoodsList() {
				if (this.finished) return
				let {
					data
				} = await goodsListApi({
					page: this.cur,
					category_id: this.currentCategory.id,
					type: 1,
					size: limit
				})
				// 是否加载完成
				this.finished = data.length < limit
				if (this.cur === 1) {
					this.goods = data
				} else {
					this.goods.push(...data)
				}
			},
			// 搜索页跳转
			searchNavigate() {
				uni.navigateTo({
					url: "/pages/common/search/search",
				});
			},
			// 分类页跳转
			kindNavigate() {
				uni.switchTab({
					url: "/pages/tabs/kind/kind",
				});
			},
			async changeIndexTag(index) {
				this.indexTagCurrent = index
				this.getHomeData()
			},
			// vip开通
			vipNavigate(type) {
				loginPrefix().then(() => {
					uni.navigateTo({
						// url: "/pages/vip/subs/open/open?type=" + type,
						url: "/pages/vip/vip?current=" + type,
					});
				});
			},
			// 商品详情
			viewInfo(id) {
				// console.log('商品id',id)
				uni.navigateTo({
					url: "/pages/goodsDetails/goodsDetails?id=" + id,
				});
			},
		},
	};
</script>
<style lang="scss" scoped>
	.sticky {
		position: sticky;
		z-index: 1000;
	}

	.head-bg {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 454rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.index-vip-user {
		width: 90%;
		margin-left: 40rpx;
	}

	.container {
		padding: 0 20rpx;
		box-sizing: border-box;
		position: relative;
		z-index: 100;
	}

	.index {
		width: 100%;
		min-height: 100vh;
		background-color: #EEEFF0;

		.search {
			background-color: skyblue;
			width: 460rpx;
			height: 60rpx;
			background-color: #e8ded6;
			border-radius: 30rpx;
			margin-left: 30rpx;
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			box-sizing: border-box;
			color: #86807d;

			.hint {
				font-size: 24rpx;
				margin-left: 10rpx;
			}
		}

		&-search {
			width: 100%;
			box-sizing: border-box;
			padding: 25rpx 30rpx;
			position: fixed;
			left: 0;
			top: 0;
			background: #fff;
			z-index: 100;

			.inner {
				background-color: #f5f5f5;
				border-radius: 30rpx;
				display: flex;
				align-items: center;
				height: 60rpx;
				box-sizing: border-box;
				padding-left: 20rpx;

				.text {
					font-size: 26rpx;
					color: #aaaaaa;
					margin-left: 10rpx;
				}
			}
		}

		&-swiper {
			margin: 0 20rpx;
		}

		&-ad {
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			background-color: #fff;
			color: #666666;
			font-size: 22rpx;
			font-weight: bold;
			position: relative;
			margin: 20rpx;
			border-radius: 10rpx;

			&-item {
				display: flex;
				align-items: center;

				.icon {
					width: 24rpx;
					height: 28rpx;
					margin-right: 15rpx;
				}
			}
		}

		&-kind {
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 0 30rpx;
			font-size: 30rpx;
			font-weight: bold;
			margin: 30rpx 0;

			&-item {
				text-align: center;

				.icon {
					width: 100rpx;
					height: 100rpx;
				}
			}
		}

		&-vip {
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 0 20rpx;

			.user {
				width: 334rpx;
				height: 220rpx;
				border-radius: 10rpx;
			}

			.right {
				width: 353rpx;
				font-size: 0;

				.city {
					margin-bottom: 20rpx;
				}

				&-img {
					width: 353rpx;
					height: 100rpx;
					border-radius: 10rpx;
				}
			}
		}

		&-content {
			margin-top: 15rpx;
			position: relative;
			z-index: 100;
		}
	}
</style>